<template>
  <div class="comment-management-container">
    <!-- 帖子选择区域 -->
    <div class="post-selection-area">
      <el-card shadow="hover" class="selection-card">
        <div slot="header" class="card-header">
          <span>帖子选择</span>
          <el-button type="primary" size="small" icon="el-icon-refresh" @click="getPosts">刷新</el-button>
        </div>
        <div class="post-search">
          <el-input
            v-model="postSearchQuery"
            placeholder="搜索帖子标题"
            prefix-icon="el-icon-search"
            clearable
            @keyup.enter.native="searchPosts"
            @clear="searchPosts">
            <el-button slot="append" icon="el-icon-search" @click="searchPosts"></el-button>
          </el-input>
        </div>
        <div class="posts-list" v-loading="postsLoading">
          <el-table
            :data="postsList"
            style="width: 100%"
            highlight-current-row
            @current-change="handlePostSelect"
            v-if="postsList.length > 0"
            :max-height="400">
            <el-table-column prop="title" label="帖子标题" min-width="180">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.title" placement="top" :disabled="scope.row.title.length < 20">
                  <span>{{ scope.row.title.length > 20 ? scope.row.title.substring(0, 20) + '...' : scope.row.title }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="发布人" width="100" align="center"></el-table-column>
            <el-table-column label="评论数" width="80" align="center">
              <template slot-scope="scope">
                <div class="comment-count-container">
                  <i class="el-icon-chat-dot-round" style="color: #409EFF;"></i>
                  <span class="comment-count">{{ scope.row.comments || 0 }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="170" align="center">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="暂无帖子数据"></el-empty>
        </div>
        <div class="pagination-container" v-if="postsList.length > 0">
          <el-pagination
            @size-change="handlePostsSizeChange"
            @current-change="handlePostsCurrentChange"
            :current-page="postsPageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="postsPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="postsTotal"
            background>
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 评论展示区域 -->
    <div class="comments-display-area">
      <el-card shadow="hover" class="comments-card">
        <div slot="header" class="card-header">
          <span>评论列表</span>
          <div class="header-actions" v-if="selectedPost">
            <el-tag type="success">当前帖子: {{ selectedPost.title }}</el-tag>
            <el-button type="primary" size="small" icon="el-icon-refresh" @click="getComments">刷新评论</el-button>
          </div>
        </div>
        
        <div v-if="!selectedPost" class="no-post-selected">
          <i class="el-icon-chat-line-square"></i>
          <p>请先从左侧选择一个帖子</p>
        </div>
        
        <div v-else class="comments-section" v-loading="commentsLoading">
          <!-- 评论搜索 -->
          <div class="comment-search">
            <el-input
              v-model="commentSearchQuery"
              placeholder="搜索评论内容"
              prefix-icon="el-icon-search"
              clearable
              @keyup.enter.native="searchComments"
              @clear="searchComments">
              <el-button slot="append" icon="el-icon-search" @click="searchComments"></el-button>
            </el-input>
          </div>
          
          <!-- 评论表格 -->
          <el-table
            :data="commentsList"
            style="width: 100%"
            row-key="commentId"
            border
            v-if="commentsList.length > 0"
            :default-expand-all="false"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column prop="commentId" label="ID" width="200" align="center"></el-table-column>
            <el-table-column prop="content" label="评论内容" min-width="220">
              <template slot-scope="scope">
                <div :class="{'parent-comment': !scope.row.parentId, 'child-comment': scope.row.parentId}">
                  <el-tag v-if="!scope.row.parentId" size="mini" type="success" class="comment-type-tag">主评论</el-tag>
                  <el-tag v-else size="mini" type="info" class="comment-type-tag">回复</el-tag>
                  <el-tooltip :content="scope.row.content" placement="top" :disabled="scope.row.content.length < 30">
                    <span>{{ scope.row.content.length > 30 ? scope.row.content.substring(0, 30) + '...' : scope.row.content }}</span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="评论人" width="120" align="center"></el-table-column>
            <el-table-column prop="createTime" label="评论时间" width="170" align="center">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button-group class="operation-btns">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button type="info" size="mini" icon="el-icon-view" @click="handleViewComment(scope.row)"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDeleteComment(scope.row)"></el-button>
                  </el-tooltip>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
          
          <el-empty v-else description="暂无评论数据"></el-empty>
          
          <!-- 评论分页 -->
          <div class="pagination-container" v-if="commentsList.length > 0">
            <el-pagination
              @size-change="handleCommentsSizeChange"
              @current-change="handleCommentsCurrentChange"
              :current-page="commentsPageNum"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="commentsPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="commentsTotal"
              background>
            </el-pagination>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 评论详情对话框 -->
    <el-dialog
      title="评论详情"
      :visible.sync="commentDetailVisible"
      width="600px"
      center>
      <div v-if="currentComment" class="comment-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="评论ID">{{ currentComment.commentId }}</el-descriptions-item>
          <el-descriptions-item label="所属帖子">{{ selectedPost ? selectedPost.title : '' }}</el-descriptions-item>
          <el-descriptions-item label="评论人">{{ currentComment.userName }}</el-descriptions-item>
          <el-descriptions-item label="评论时间">{{ formatDate(currentComment.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="评论内容">
            <div class="comment-full-content">{{ currentComment.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentComment.parentId" label="父评论ID">
            {{ currentComment.parentId }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commentDetailVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'CommentsList',
  data() {
    return {
      // 帖子列表相关
      postsList: [],
      postsLoading: false,
      postsPageNum: 1,
      postsPageSize: 10,
      postsTotal: 0,
      postSearchQuery: '',
      selectedPost: null,
      
      // 评论列表相关
      commentsList: [],
      commentsLoading: false,
      commentsPageNum: 1,
      commentsPageSize: 10,
      commentsTotal: 0,
      commentSearchQuery: '',
      
      // 评论详情相关
      commentDetailVisible: false,
      currentComment: null
    };
  },
  created() {
    this.getPosts();
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取帖子列表
    getPosts() {
      this.postsLoading = true;
      service.get('/api/forum/post/getPostLists', {
        params: {
          pageNum: this.postsPageNum,
          pageSize: this.postsPageSize,
          title: this.postSearchQuery
        }
      })
        .then(res => {
          if (res.code === 200) {
            this.postsList = res.data.list || [];
            this.postsTotal = res.data.total || 0;
          } else {
            this.$message.error(res.msg || '获取帖子列表失败');
          }
        })
        .catch(error => {
          console.error('获取帖子列表出错:', error);
          this.$message.error('网络错误，请稍后重试');
        })
        .finally(() => {
          this.postsLoading = false;
        });
    },
    
    // 搜索帖子
    searchPosts() {
      this.postsPageNum = 1;
      this.getPosts();
    },
    
    // 帖子分页大小变化
    handlePostsSizeChange(newSize) {
      this.postsPageSize = newSize;
      this.getPosts();
    },
    
    // 帖子当前页变化
    handlePostsCurrentChange(newPage) {
      this.postsPageNum = newPage;
      this.getPosts();
    },
    
    // 选择帖子
    handlePostSelect(row) {
      if (row) {
        this.selectedPost = row;
        this.commentsPageNum = 1;
        this.commentSearchQuery = '';
        this.getComments();
      }
    },
    
    // 获取评论列表
    getComments() {
      if (!this.selectedPost) return;
      
      this.commentsLoading = true;
      service.get('/api/forum/comment/getCommentsByPost', {
        params: {
          postId: this.selectedPost.postId,
          content: this.commentSearchQuery,
          pageNum: this.commentsPageNum,
          pageSize: this.commentsPageSize
        }
      })
        .then(res => {
          if (res.code === 200) {
            // 处理评论数据，构建父子关系
            const comments = res.data.list || [];
            this.commentsTotal = res.data.total || 0;
            
            // 将评论按照父子关系组织
            this.organizeComments(comments);
          } else {
            this.$message.error(res.msg || '获取评论列表失败');
          }
        })
        .catch(error => {
          console.error('获取评论列表出错:', error);
          this.$message.error('网络错误，请稍后重试');
        })
        .finally(() => {
          this.commentsLoading = false;
        });
    },
    
    // 组织评论的父子关系
    organizeComments(comments) {
      // 创建一个映射表，用于快速查找评论
      const commentMap = {};
      const rootComments = [];
      
      // 第一遍遍历，建立映射关系
      comments.forEach(comment => {
        // 确保每个评论都有一个children数组
        comment.children = [];
        commentMap[comment.commentId] = comment;
      });
      
      // 第二遍遍历，建立父子关系
      comments.forEach(comment => {
        if (comment.parentId) {
          // 这是一个子评论
          const parent = commentMap[comment.parentId];
          if (parent) {
            // 将子评论添加到父评论的children中
            parent.children.push(comment);
          } else {
            // 如果找不到父评论，就当作根评论处理
            rootComments.push(comment);
          }
        } else {
          // 这是一个根评论
          rootComments.push(comment);
        }
      });
      
      // 更新评论列表
      this.commentsList = rootComments;
    },
    
    // 搜索评论
    searchComments() {
      this.commentsPageNum = 1;
      this.getComments();
    },
    
    // 评论分页大小变化
    handleCommentsSizeChange(newSize) {
      this.commentsPageSize = newSize;
      this.getComments();
    },
    
    // 评论当前页变化
    handleCommentsCurrentChange(newPage) {
      this.commentsPageNum = newPage;
      this.getComments();
    },
    
    // 查看评论详情
    handleViewComment(comment) {
      this.currentComment = comment;
      this.commentDetailVisible = true;
    },
    
    // 删除评论
    handleDeleteComment(comment) {
      this.$confirm('此操作将永久删除该评论及其所有回复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/forum/comment/deleteComment/${comment.commentId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getComments();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除评论出错:', error);
          this.$message.error('网络错误，请稍后重试');
        });
      }).catch(() => {
        // 取消删除
      });
    }
  }
};
</script>

<style scoped>
.comment-management-container {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.post-selection-area {
  flex: 1;
  min-width: 300px;
  max-width: 600px;
}

.comments-display-area {
  flex: 2;
  min-width: 500px;
}

.selection-card,
.comments-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.post-search,
.comment-search {
  margin-bottom: 15px;
}

.posts-list {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.no-post-selected {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #909399;
}

.no-post-selected i {
  font-size: 48px;
  margin-bottom: 10px;
}

.parent-comment {
  font-weight: 500;
  background-color: #f8f8f8;
  padding: 8px;
  border-radius: 4px;
}

.child-comment {
  color: #606266;
  padding: 8px 8px 8px 16px;
  background-color: #f1f7ff;
  border-radius: 4px;
}

.comment-type-tag {
  margin-right: 8px;
}

.comment-count-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.comment-count {
  margin-left: 5px;
  font-weight: bold;
}

.comment-full-content {
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.operation-btns .el-button {
  padding: 7px 12px;
}
</style> 